var MyLinkedList = function() {
  this.head = null
  this.tail = null
  this.length = 0
};

/** 
* @param {number} index
* @return {number}
*/
MyLinkedList.prototype.get = function(index) {
  if(index < 0 || index >= this.length) return -1
  let cur = this.head
  while(index--){
      cur = cur.next
  }
  return cur.val
};

/** 
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtHead = function(val) {
  let newNode = new ListNode(val,null)
  if(this.length === 0){
      this.head = newNode
      this.tail = newNode
  }else{
      newNode.next = this.head
      this.head = newNode
  }
  this.length++
};

/** 
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtTail = function(val) {
  let newNode = new ListNode(val,null)
  if(this.length === 0){
      this.head = newNode
      this.tail = newNode
  }else{
      this.tail.next = newNode
      this.tail = newNode
  }
  this.length++
};

/** 
* @param {number} index 
* @param {number} val
* @return {void}
*/
MyLinkedList.prototype.addAtIndex = function(index, val) {
  if(index <= 0){
      this.addAtHead(val)
      return 
  }
  if(index === this.length){
      this.addAtTail(val)
      return
  }
  if(index > this.length) return
  let newNode = new ListNode(val,null)
  let cur = this.head
  let pre = null
  while(index--){
      pre = cur
      cur = cur.next
  }
  pre.next = newNode
  newNode.next = cur
  this.length++
};

/** 
* @param {number} index
* @return {void}
*/
MyLinkedList.prototype.deleteAtIndex = function(index) {
  if(index < 0 || index >= this.length) return
  if(index === 0) {
      this.head = this.head.next
  }else{
      let cur = this.head
      let pre = null
      while(index--){
          pre = cur
          cur = cur.next
      }
      pre.next = cur.next
      if(pre.next === null){
          this.tail = pre
      }
  }
  this.length--
};

/**
* Your MyLinkedList object will be instantiated and called as such:
* var obj = new MyLinkedList()
* var param_1 = obj.get(index)
* obj.addAtHead(val)
* obj.addAtTail(val)
* obj.addAtIndex(index,val)
* obj.deleteAtIndex(index)
*/